#include "logLinux.h"

#ifdef __linux__

xxhhdzl::log::log(size_t flag)
	: lwLog(flag)
{}

xxhhdzl::log::~log()
{
    switch (_flag)
    {
    case 0:
        outputClassfile();
        break;
    case 1:
        break;
    case 2:
        outputOnefile();
        break;
    case 3:
        outputOnefile();
        break;
    case 4:
        outputClassfile();
        break;
    default:
        operator()(Error, 98, "flag set error");
        for (auto s : _log)
        {
            std::cout << s << std::endl;
        }
        break;
    }
}

bool xxhhdzl::log::outputOnefile()
{
    int fd = open("./log.log", O_CREAT | O_WRONLY | O_APPEND, 0666);
    if (fd == -1)
    {
        operator()(Error, __LINE__, "uotputOnefile create file lose");
        return false;
    }

    {
        std::unique_lock<std::mutex> lock(std::mutex);
        for (auto s : _log)
        {
            int c = write(fd, s.c_str(), s.size());
            if (c == -1)
            {
                operator()(Error, __LINE__, "write file lose");
                return false;
            }
        }
    }

    close(fd);
    return true;
}

bool xxhhdzl::log::outputClassfile()
{
    mkdir("./log", 0777);

    std::vector<int> fd(6);
    for (int i = 0; i <= 5; i++)
    {
        std::string s = "./log/";
        s += "log_" + getGrade(i);
        s += ".log";
        int c = open(s.c_str(), O_CREAT | O_WRONLY | O_APPEND, 0666);
        if (c == -1)
        {
            operator()(Error, __LINE__, "uotputClassfile create file lose");
            return false;
        }
        fd[i] = c;
    }

    {
        std::unique_lock<std::mutex> lock(std::mutex);
        for (auto s : _log)
        {
            int end = s.find("]");
            std::string t = s.substr(1, end - 1);

            int c = write(fd[Grade(t)], s.c_str(), s.size());
            if (c == -1)
            {
                operator()(Error, __LINE__, "write file lose");
                return false;
            }
        }
    }

    for (auto f : fd)
    {
        close(f);
    }
    return true;
}

#endif